package com.syh.jn.scm.domain.supplier.entity.base;

import cn.redscarf.commons.util.bean.ExtBeanUtils;
import cn.redscarf.commons.spring.SpringContextUtils;
import com.syh.jn.scm.domain.supplier.repository.base.SalesmanReadRepository;
import com.syh.jn.scm.domain.support.SuperBusinessAggregate;
import com.syh.jn.scm.dto.supplier.base.salesTeam.SalesTeamMto;
import com.syh.jn.scm.dto.supplier.base.salesTeam.SalesTeamSto;
import com.syh.jn.scm.exception.BusinessException;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.util.UUID;

/**
 * 销售团队管理
 */
@Data
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
public class SalesTeam extends SuperBusinessAggregate<Long> {

  /**
   * 创建销售团队
   *
   * @param sto
   * @return
   */
  public static SalesTeam createdSalesTeamBySupply(SalesTeamSto sto) {
    if (sto.getSalesmanId() != null) {
      SalesmanReadRepository salesmRead = (SalesmanReadRepository) SpringContextUtils.getBean(SalesmanReadRepository.class);
      Salesman sm = salesmRead.getById(sto.getSalesmanId());
      if (!sm.getStatus().equals(Short.valueOf("1")))
        throw new BusinessException("销售代表未启用，创建失败");
    }
    //初始化创建
    SalesTeam salesTeam = SalesTeam.commonCreatedSalesTeam();
    ExtBeanUtils.copyProperties(sto, salesTeam);
    salesTeam.setUuid(UUID.randomUUID().toString());

    return salesTeam;
  }

  /**
   * 修改销售团队
   *
   * @param mto
   * @return
   */
  public void modify(SalesTeamMto mto) {
    if (mto.getSalesmanId() != null) {
      SalesmanReadRepository salesmRead = (SalesmanReadRepository) SpringContextUtils.getBean(SalesmanReadRepository.class);
      Salesman sm = salesmRead.getById(mto.getSalesmanId());
      if (!sm.getStatus().equals(Short.valueOf("1")))
        throw new BusinessException("销售代表未启用，修改失败");
    }
    ExtBeanUtils.copyProperties(mto, this);
    this.lastUpdateTimeStamp = System.currentTimeMillis();
  }

  /**
   * 删除销售团队
   */
  public void destroy() {

  }

  /**
   * 初始化销售团队
   *
   * @return
   */
  public static SalesTeam commonCreatedSalesTeam() {
    SalesTeam salesTeam = new SalesTeam();
    salesTeam.status = 1;
    salesTeam.createTimeStamp = System.currentTimeMillis();
    salesTeam.lastUpdateTimeStamp = System.currentTimeMillis();

    return salesTeam;
  }

  /**
   * 启用
   */
  public void enabled() {
    this.status = 1;
    this.lastUpdateTimeStamp = System.currentTimeMillis();
  }

  /**
   * 停用
   */
  public void disabled() {
    this.status = -1;
    this.lastUpdateTimeStamp = System.currentTimeMillis();
  }

  /**
   * 名称
   */
  private String name;
  /**
   * 编号
   */
  private String code;
  /**
   * 团队领导人
   */
  private Long salesmanId;
  /**
   * 描述
   */
  private String description;
  /**
   * 状态( -1:停用, 1:启用)
   */
  private Short status;
  /**
   * 排序等级
   */
  private Integer orderLevel;
}
